<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="主题" prop="ehpTitle">
        <el-input
          v-model="queryParams.ehpTitle"
          placeholder="请输入主题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="ehpContacts">
        <el-input
          v-model="queryParams.ehpContacts"
          placeholder="请输入联系人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="ehpContactNumber">
        <el-input
          v-model="queryParams.ehpContactNumber"
          placeholder="请输入联系电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="ehpStatus">
        <el-select
          v-model="queryParams.ehpStatus"
          placeholder="请输入状态"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="ehActivitiesReleaseList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="ehpId" header-align="center" align="center" label="编号"></el-table-column>
      <el-table-column prop="ehpTitle" header-align="center" align="center" label="主题"></el-table-column>
      <el-table-column header-align="center" align="center" label="主题图片">
        <template slot-scope="scope">
          <img style="width:100px; height:100px" :src="scope.row.ehpPic" />
        </template>
      </el-table-column>
      <el-table-column prop="ehGridName" header-align="center" align="center" label="所属网格"></el-table-column>
      <el-table-column prop="ehpContacts" header-align="center" align="center" label="联系人"></el-table-column>
      <el-table-column prop="ehpContactNumber" header-align="center" align="center" label="联系电话"></el-table-column>
      <el-table-column prop="ehpAddress" header-align="center" align="center" label="活动地址"></el-table-column>
      <el-table-column prop="ehpUserCount" header-align="center" align="center" label="活动名额"></el-table-column>
      <el-table-column prop="ehpBonusPoints" header-align="center" align="center" label="积分奖励"></el-table-column>
      <el-table-column prop="ehpCreateTime" header-align="center" align="center" label="创建时间"></el-table-column>
      <el-table-column prop="ehpStatus" header-align="center" align="center" label="状态">
        <template scope="scope">
<p v-if="scope.row.ehpStatus==0">待审核</p>
<p v-if="scope.row.ehpStatus==1">审核失败</p>
<p v-if="scope.row.ehpStatus==2">已审核</p>
<p v-if="scope.row.ehpStatus==3">报名中</p>
<p v-if="scope.row.ehpStatus==4">未开始</p>
<p v-if="scope.row.ehpStatus==5">进行中</p>
<p v-if="scope.row.ehpStatus==6">已结束</p>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.ehpStatus==0" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-info" @click="handleInfo(scope.row)">查看活动</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="主题" prop="ehpTitle">
              <el-input v-model="form.ehpTitle" placeholder="请输入主题" :disabled="disabled"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主题图片" prop="ehpPic">
              <el-upload
                class="avatar-uploader"
                name="files"
                :data="userData"
                :action="commitimg"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :disabled="disabled"
              >
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="ehpStatus">
              <el-select
                v-model="form.ehpStatus"
                disabled="true"
                placeholder="请输入状态"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="!form.ehpUnlimitedUsers || form.ehpUnlimitedUsers == 'false'" label="活动名额" prop="ehpUserCount">
              <el-input-number
                v-model="form.ehpUserCount"
                @change="handleChange"
                :min="1"
                aria-label="请输入活动名额"
                :disabled="disabled"
              />
            </el-form-item>
            <el-form-item label="报名截止时间" label-width="100" prop="ehpSignFinishTime">
              <el-date-picker
                v-model="form.ehpSignFinishTime"
                type="datetime"
                placeholder="请输入报名截止时间"
                clearable
                size="small"
                :disabled="disabled"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="招募要求" prop="ehpRequirement">
              <el-input
                type="textarea"
                :rows="3"
                v-model="form.ehpRequirement"
                placeholder="请输入招募要求"
                :disabled="disabled"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="活动地址" prop="ehpAddress">
              <el-input v-model="form.ehpAddress" placeholder="请输入活动地址" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人" prop="ehpContacts">
              <el-input v-model="form.ehpContacts" placeholder="请输入联系人" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="ehpContactNumber">
              <el-input v-model="form.ehpContactNumber" placeholder="请输入联系电话" max="11" min="11" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="积分奖励" prop="ehpBonusPoints">
              <el-input-number v-model="form.ehpBonusPoints" :precision="2" placeholder="请输入积分奖励" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="不限名额" prop="ehpUnlimitedUsers" style="margin-left:50px;">
              <el-switch
                v-model="form.ehpUnlimitedUsers"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :disabled="disabled"
              ></el-switch>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="9" v-if="!form.ehpUnlimitedUsers || form.ehpUnlimitedUsers == 'false'">
            <el-form-item label="剩余名额" prop="ehpUserCountBalance">
              <el-input-number
                v-model="form.ehpUserCountBalance"
                @change="handleChange"
                :min="1"
                aria-label="请输入剩余名额"
              />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动开始时间" label-width="60" prop="ehpStartTime">
              <el-date-picker
                v-model="form.ehpStartTime"
                type="datetime"
                placeholder="请输入报名开始时间"
                clearable
                size="small"
                :disabled="disabled"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动结束时间" label-width="60" prop="ehpFinishTime">
              <el-date-picker
                v-model="form.ehpFinishTime"
                type="datetime"
                placeholder="请输入活动结束时间"
                clearable
                size="small"
                :disabled="disabled"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动详情" prop="ehpContent">
              <Editor v-model="form.ehpContent" :disabled="disabled"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="3">
            <el-form-item label prop="ehpId">
              <el-input type="hidden" v-model="form.ehpId" :disabled="disabled" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="disabled == false">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listEhActivitiesRelease,
  getEhActivitiesRelease,
  delEhActivitiesRelease,
  addEhActivitiesRelease,
  updateEhActivitiesRelease
} from "@/api/volunteer/ehactivitiesrelease";
import Editor from "@/components/Editor";
import Cookies from "js-cookie";
export default {
  name: "EhActivitiesRelease",
  components: {
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      disabled:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      ehActivitiesReleaseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 图片
      imageUrl: "",
      //图片上传
      commitimg: process.env.VUE_APP_BASE_API + "/minio/api/minio/file/upload",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ehpUid:undefined,
        ehpStatus: undefined,
        ehpTitle: undefined,
        ehpAddress: undefined,
        ehpUserCount: undefined,
        ehpContacts: undefined,
        ehpContactNumber: undefined,
        ehpBonusPoints: undefined,
        ehpUnlimitedUsers: undefined,
        ehpUserCountBalance: undefined
      },
      options: [
        {
          value: 0,
          label: "待审核"
        },
        {
          value: 1,
          label: "审核失败"
        },
        {
          value: 2,
          label: "已审核"
        },
        {
          value: 3,
          label: "报名中"
        },
        {
          value: 4,
          label: "未开始"
        },
        {
          value: 5,
          label: "进行中"
        },
        {
          value: 6,
          label: "已结束"
        }
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ehpStatus: [
          {
            required: true,
            message: "状态不能为空",
            trigger: "blur"
          }
        ],
        ehpTitle: [
          { required: true, message: "主题不能为空", trigger: "blur" }
        ],
        ehpPic: [
          { required: true, message: "主题图片不能为空", trigger: "blur" }
        ],
        ehpSignFinishTime: [
          { required: true, message: "报名截止时间不能为空", trigger: "blur" }
        ],
        ehpStartTime: [
          { required: true, message: "活动开始时间不能为空", trigger: "blur" }
        ],
        ehpFinishTime: [
          { required: true, message: "活动结束时间不能为空", trigger: "blur" }
        ],
        ehpAddress: [
          { required: true, message: "活动地址不能为空", trigger: "blur" }
        ],
        ehpUserCount: [
          { required: true, message: "活动名额不能为空", trigger: "blur" }
        ],
        ehpContacts: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ],
        ehpContactNumber: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
        ehpBonusPoints: [
          { required: true, message: "积分奖励不能为空", trigger: "blur" }
        ],
        ehpUserCountBalance: [
          { required: true, message: "剩余名额不能为空", trigger: "blur" }
        ],
        ehpContent: [
          { require: true, message: "活动详情不能为空", trigger: "blur" }
        ],
        ehpRequirement: [
          { require: true, message: "招募要求不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查看按钮操作 */
    handleInfo(row) {
      const ehpId = row.ehpId || this.ids;
      getEhActivitiesRelease(ehpId).then(response => {
        this.form = response.data;
        console.log('this.form ',this.form)
        this.imageUrl = this.form.ehpPic;
        this.open = true;
        this.title = "查看活动";
        this.disabled = true;
      });
    },
    //时间戳转日期字符串
    formatDate(date) {
        var y = date.getFullYear();  
                var m = date.getMonth() + 1;  
                m = m < 10 ? ('0' + m) : m;  
                var d = date.getDate();  
                d = d < 10 ? ('0' + d) : d;  
                var h = date.getHours();  
                h=h < 10 ? ('0' + h) : h;  
                var minute = date.getMinutes();  
                minute = minute < 10 ? ('0' + minute) : minute;  
                var second=date.getSeconds();  
                second=second < 10 ? ('0' + second) : second;  
                return y + '-' + m + '-' + d+'T'+h+':'+minute+':'+second; 
    },
    /** 查询审核通过的活动列表 */
    getList() {
      this.loading = true;
      this.queryParams.ehpUid = Cookies.get("ehuId");
      listEhActivitiesRelease(this.queryParams).then(response => {
        this.ehActivitiesReleaseList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 岗位状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.disabled = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.imageUrl = "";
      this.disabled = false;
      this.form = {
        ehpTitle: undefined,
        ehpStatus: undefined,
        ehpPic: undefined,
        ehpSignFinishTime: undefined,
        ehpStartTime: undefined,
        ehpFinishTime: undefined,
        ehpAddress: undefined,
        ehpUserCount: 1,
        ehpContacts: undefined,
        ehpContactNumber: undefined,
        ehpBonusPoints: 1.0,
        ehpUnlimitedUsers: undefined,
        ehpUserCountBalance: 1,
        ehpRequirement: undefined,
        ehpContent: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ehpId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加活动";
      this.form.ehpGridId =  Cookies.get("ehuGridId");
      this.form.ehpUid = Cookies.get("ehuId");
      this.form.ehpStatus = 0;
      this.form.ehpUnlimitedUsers = false;//不限名额默认未false
      console.log(this.form)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ehpId = row.ehpId || this.ids;
      getEhActivitiesRelease(ehpId).then(response => {
        this.form = response.data;
        this.form.ehpSignFinishTime = new Date(this.form.ehpSignFinishTime);
        this.form.ehpStartTime = new Date(this.form.ehpStartTime);
        this.form.ehpFinishTime = new Date(this.form.ehpFinishTime);
        console.log('this.form ',this.form)
        this.imageUrl = this.form.ehpPic;
        this.open = true;
        this.title = "修改活动";
        this.form.ehpStatus = 0;
      });
    },
    // 单个文件上传成功时
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.ehpPic = res.imgArr[0];
      console.log("图片上传", this.form.ehpPic);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能上传jpg/png文件!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return (isJPG || isPNG) && isLt2M;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 提交按钮 */
    submitForm: function() {
      this.form.ehpUserCountBalance = this.form.ehpUserCount;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.ehpUnlimitedUsers == true){
            this.form.ehpUserCount = undefined;
            this.form.ehpUserCountBalance = undefined;
          }
          const  FinishTime =new Date(this.form.ehpFinishTime).getTime();//结束时间
          const  StartTime =new Date(this.form.ehpStartTime).getTime();//开始时间
          const  SignFinishTime =new Date(this.form.ehpSignFinishTime).getTime();//报名截止时间
          this.form.ehpFinishTime = this.formatDate(new Date(this.form.ehpFinishTime));
          this.form.ehpStartTime = this.formatDate(new Date(this.form.ehpStartTime));
          this.form.ehpSignFinishTime = this.formatDate(new Date(this.form.ehpSignFinishTime));

          //判断输入框内容
          if(!(/^1[3456789]\d{9}$/.test(this.form.ehpContactNumber))){
            return this.msgError('请输入正确的手机号');
          }else if(SignFinishTime >= StartTime){
            return this.msgError('报名截止时间必须小于活动开始时间');
          }else if(StartTime >= FinishTime){
            return this.msgError('活动开始时间必须小于活动结束时间');
          }

          if (this.form.ehpId != undefined) {
            //增加判断
            this.form.ehpGridId =  Cookies.get("ehuGridId");
            this.form.ehpUid = Cookies.get("ehuId");
            
            updateEhActivitiesRelease(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addEhActivitiesRelease(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ehpIdList = row.ehpId || this.ids;
      this.$confirm(
        '是否确认删除审核通过的活动编号为"' + ehpIdList + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delEhActivitiesRelease(ehpIdList);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.el-textarea .el-textarea__inner {
  resize: none;
}
</style>